<script name="CallbackBind" lang="ts" setup>
import { QQUserInfo } from '@/types/user'
import { codeRule, mobileRule } from '@/utils/validate'
import { useField, useForm } from 'vee-validate'
import { useCountDown } from '@/utils/hooks'
import { ref } from 'vue'
import useStore from '@/store'
import Message from '@/components/message'
import router from '@/router'
const props = defineProps({
  openID: {
    type: String,
    required: true
  }
})
const { user } = useStore()
// 情况2 有手机号 和QQ和做一次绑定
const info = ref<QQUserInfo>({} as QQUserInfo)
//获取用户信息
QC.api('get_user_info').success((res: any) => {
  info.value = res.data
})
const { validate } = useForm({
  validationSchema: {
    mobile: mobileRule,
    code: codeRule
  }
})
const { value: mobile, errorMessage: mobileErrMsg, validate: validateMobie } = useField<string>('mobile')
const { value: code, errorMessage: codeErrMsg } = useField<string>('code')
const mobileRef = ref()
const { time, start } = useCountDown()
// 发送验证码
const sendCode = async () => {
  if (time.value > 0) return // 倒计时期间, 禁止重复点击
  // 1. 校验手机号的合法性
  const res = await validateMobie()
  // 2. 如果没有输入手机号 让手机号的输入框自动获取校验
  if (!res.valid) return mobileRef.value.focus()
  // 先发送请求, 再开始倒计时
  await user.sendQQbindMsg(mobile.value)
  Message.success('验证码已发送')
  // 3.开启倒计时
  start()

}
// 绑定手机号
const handleSubmit = async () => {
  // 1.预校验
  const res = await validate()
  if (!res.valid) return
  // 2. 发送绑定的请求
  await user.bindQQLogin(props.openID, mobile.value, code.value)
  // 3.提示
  Message.success('绑定成功')
  // 4.跳转
  router.push('/')
}
</script>
<template>
  <div class="xtx-form">
    <div class="user-info">
      <img :src="info.figureurl_qq_1" alt="" />
      <p>Hi，{{ info.nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input ref="mobileRef" class="input" v-model="mobile" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error">{{ mobileErrMsg }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input class="input" v-model="code" type="text" placeholder="短信验证码" />
        <span class="code" @click="sendCode">{{ time > 0 ? `${time}s后发送` : `发送验证码` }}</span>
      </div>
      <div class="error">{{ codeErrMsg }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="handleSubmit">立即绑定</a>
  </div>
</template>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;

  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }

  p {
    padding-left: 10px;
  }
}

.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;

  &:hover {
    cursor: pointer;
  }
}
</style>